package neu.dreamera.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

import neu.dreamera.R;

/**
 * Created by root on 16-6-24.
 */
public class ReFlashlistView extends ListView implements OnScrollListener {

    View header;//headerview
    int headerheight;
    int firstVisibleItem;//first visible item location

    int scrollState;

    boolean isRemark;
    int startY;

    int state;//state
    final int NONE=0;//normal
    final int PULL = 1;// 提示下拉状态；
    final int RELESE = 2;// 提示释放状态；
    final int REFLASHING = 3;// 刷新状态；

    IReflashListener iReflashListener;//update data interface

    public ReFlashlistView(Context context) {
        super(context);
        initView(context);
    }

    public ReFlashlistView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ReFlashlistView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    /**
     * init the view,add headerview to listview
     * @param context
     */
    private void initView(Context context){
        LayoutInflater inflater=LayoutInflater.from(context);
        header =inflater.inflate(R.layout.header_layout,null);
        measureView(header);
        headerheight=header.getMeasuredHeight();
        Log.i("tag","headerHeight="+headerheight);
        topPadding(-headerheight);
        this.addHeaderView(header);
        this.setOnScrollListener((OnScrollListener) this);
    }

    /**
     * 通知父布局占用的宽和高
     * @param view
     */
    private void  measureView(View view){
        ViewGroup.LayoutParams p=view.getLayoutParams();
        if(p==null){
            p=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int width=ViewGroup.getChildMeasureSpec(0,0,p.width);
        int height;
        int tempheight=p.height;
        if(tempheight>0){
            height=MeasureSpec.makeMeasureSpec(tempheight,MeasureSpec.EXACTLY);
        }else{
            height=MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED);
        }
        view.measure(width,height);
    }

    /**
     * 设置header布局的上边距
     * @param topPadding
     */
    private void topPadding(int topPadding){
        header.setPadding(header.getPaddingLeft(),topPadding,header.
                getPaddingRight(),header.getPaddingBottom());
        header.invalidate();

    }


    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        this.firstVisibleItem = firstVisibleItem;
    }


    public void onScrollStateChanged(AbsListView view, int scrollState) {

        this.scrollState = scrollState;
    }

    public boolean onTouchEvent(MotionEvent ev){
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(firstVisibleItem==0){
                    isRemark = true;
                    startY = (int) ev.getY();

                }

                break;
            case MotionEvent.ACTION_MOVE:
                noMove(ev);
                break;
            case MotionEvent.ACTION_UP:
                if(state==RELESE){
                    state=REFLASHING;
                    reflashViewBystate();

                    iReflashListener.onReflash();
                }
                else if(state==PULL){
                    state=NONE;
                    isRemark=false;
                    reflashViewBystate();

                }
                break;



        }
        return super.onTouchEvent(ev);

    }

    /**
     * motion operate
     * @param ev
     */
    private void noMove(MotionEvent ev){
        if(!isRemark){
            return;
        }
        int tempY=(int)ev.getY();
        int space=tempY-startY;
        int topPadding = space - headerheight;
        switch (state){
            case NONE:
                if(space>0){
                    state=PULL;
                    reflashViewBystate();
                }
                break;
            case PULL:
                topPadding(topPadding);
                if(space>headerheight+30&&scrollState==SCROLL_STATE_TOUCH_SCROLL){
                    state=RELESE;
                    reflashViewBystate();

                }
                break;
            case RELESE:
                topPadding(topPadding);
                if(space<headerheight+30){
                    state=PULL;
                    reflashViewBystate();

                }else if(space<=0){
                    state=NONE;
                    isRemark=false;
                    reflashViewBystate();
                }
                break;
        }
    }

    /**
     * change the view by state
     */
    private void reflashViewBystate() {

        TextView tip = (TextView) header.findViewById(R.id.pullrefersh_tip);
        ImageView arrow = (ImageView) header.findViewById(R.id.pullrefresh_arrow);
        ProgressBar progress = (ProgressBar) header.findViewById(R.id.pullrefersh_progess);
        RotateAnimation anim = new RotateAnimation(0, 180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);//
        anim.setDuration(500);
        anim.setFillAfter(true);
        RotateAnimation anim1 = new RotateAnimation(180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);//

        anim1.setDuration(500);
        anim1.setFillAfter(true);
        switch (state) {
            case NONE:
                arrow.clearAnimation();
                topPadding(-headerheight);
                break;
            case PULL:
                arrow.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                tip.setText("下拉可以刷新");
                arrow.clearAnimation();
                arrow.setAnimation(anim);
                break;
            case RELESE:
                arrow.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                tip.setText("松开可以刷新");
                arrow.clearAnimation();
                arrow.setAnimation(anim1);
                break;
            case REFLASHING:
                topPadding(50);//50
                arrow.setVisibility(View.GONE);
                progress.setVisibility(View.VISIBLE);
                tip.setText("正在刷新......");
                arrow.clearAnimation();
                break;
        }
    }
    /**
     *
     */
    public void reflashComplete(){
        state = NONE;
        isRemark=false;
        reflashViewBystate();
        TextView lastupdatetime= (TextView) header.findViewById(R.id.pullrefersh_lastupdate_time);
        SimpleDateFormat format = new SimpleDateFormat("yyy年MM月dd日hh:mm:ss:");
        Date date =new Date(System.currentTimeMillis());
        String time=format.format(date);
        lastupdatetime.setText(time);
    }

    public  void setInterface(IReflashListener iReflashListener){
        this.iReflashListener=iReflashListener;
    }

    /**
     *
     */


    public interface IReflashListener{
        public void onReflash();
    }

}
